package com.plat.util;

import net.sf.json.JSONException;

import org.hibernate.collection.internal.PersistentSet;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;

public class LazyJsonUtils extends JsonTools {

	private static LazyJsonUtils instance = null;

	public static String toJSONString(Object obj) throws JSONException {
		return toJSONString(obj, false);
	}

	public static String toJSONString(Object obj, boolean useClassConvert) throws JSONException {
		if (instance == null)
			instance = new LazyJsonUtils();
		return instance.getJSONObject(obj, useClassConvert).toString();
	}

	@Override
	protected Object proxyCheck(Object bean) {
		System.out.println("Class is " + bean.getClass().getName());
		if (bean instanceof HibernateProxy) {
			LazyInitializer lazyInitializer = ((HibernateProxy) bean).getHibernateLazyInitializer();
			if (lazyInitializer.isUninitialized()) {
				System.out.println(">>>>>lazyInitializer.getIdentifier()=" + lazyInitializer.getIdentifier());
				return lazyInitializer.getIdentifier();
			}
		}
		if (bean instanceof PersistentSet) {
			return new String[] {}; // 忽略hibernate one-to-many
		}
		return bean;
	}
}
